import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../services/ScreenAdaper.dart';
import '../../config/Config.dart';
import 'package:dio/dio.dart';
import '../../model/Kinds.dart';
import '../../model/Data02.dart';

class CategoryPage extends StatefulWidget {
  const CategoryPage({Key? key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

// class _CategoryPageState extends State<CategoryPage> {
//   @override
//   Widget build(BuildContext context) {
//     return Text(
//       '我是分类组件'
//     );
//   }
// }

class _CategoryPageState extends State with AutomaticKeepAliveClientMixin {
  int _selectIndex = 0;
  List _leftCateList = [];
  List _rightCateList = [];
  @override
  bool get wantKeepAlive => true; // 缓存页面重要代码
  @override
  void initState() {
    super.initState();
    print('刷新了分类页面');
    _getLeftCateData();
  }

  /// 获取左侧列表数据
  _getLeftCateData() async {
    // print('11111---1');
    String api = '${Config.domain}kind/all';
    var result = await Dio().get(api);
    // print('11111---2');
    // print(result);
    var leftList = KindsObj.fromJson(result.data);
    setState(() {
      this._leftCateList = leftList.product;
    });
    _getRightCateData(leftList.product[0].pid.toString());
  }

  /// 获取右侧列表数据
  _getRightCateData(pid) async {
    String api = '${Config.domain}kind/new?kid=' + pid;
    print('22222---1');
    print(api);
    var result = await Dio().get(api);
    print('22222---2');
    print(result);
    var focusList = BottomObj.fromJson(result.data);
    setState(() {
      this._rightCateList = focusList.product;
    });
    print(' this._rightCateList.length');
    print(this._rightCateList.length);
  }

  Widget _leftCateWidget(leftWidth) {
    if (this._leftCateList.length > 0) {
      return Container(
        width: leftWidth,
        height: double.infinity,
        // color: Colors.red,
        child: ListView.builder(
          itemCount: this._leftCateList.length, // 改为真实数据
          itemBuilder: (context, index) {
            return Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    setState(() {
                      _selectIndex = index;
                      this._getRightCateData(
                          this._leftCateList[index].pid.toString()); // 添加变动事件
                    });
                  },
                  child: Container(
                    width: double.infinity,
                    height: ScreenUtil().setHeight(76.h),
                    padding: EdgeInsets.only(top: 30.h),
                    child: Text("${this._leftCateList[index].kindName}",
                        textAlign: TextAlign.center),
                    color: _selectIndex == index
                        ? Color.fromRGBO(240, 246, 246, 0.9)
                        : Colors.white,
                  ),
                ),
                Divider(height: 1) // 这个主要是为了控制上下的间距不要有奇怪的空白
              ],
            );
          },
        ),
      );
    } else {
      return Container(
        width: leftWidth,
        height: double.infinity,
      );
    }
  }

  _rightCateWidget(rightItemWidth, rightItemHeight) {
    if (this._rightCateList.length > 0) {
      return Expanded(
        flex: 1,
        child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  childAspectRatio: rightItemWidth / rightItemHeight,
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10),
              itemCount: this._rightCateList.length, //动态数据
              itemBuilder: (context, index) {
                String pic =
                    '${Config.domain + this._rightCateList[index].img}';
                return InkWell(
                    onTap: () {
                      print('打印此时的ID');
                      print(this._rightCateList[index].productId);
                      Navigator.pushNamed(context, '/productList', arguments: {
                        'productId': this._rightCateList[index].productId
                      });
                    },
                    child: Container(
                      // padding: EdgeInsets.all(10),
                      child: Column(
                        children: <Widget>[
                          AspectRatio(
                            aspectRatio: 1 / 1,
                            child: Image.network("${pic}", fit: BoxFit.cover),
                          ),
                          Container(
                            height: ScreenUtil().setHeight(40),
                            child: Text(
                                '${this._leftCateList[this._selectIndex].kindName}-${this._rightCateList[index].cakeName}'),
                          )
                        ],
                      ),
                    ));
              },
            )),
      );
    } else {
      return Expanded(
          flex: 1,
          child: Container(
            padding: EdgeInsets.all(10),
            height: double.infinity,
            color: Color.fromRGBO(240, 246, 246, 0.9),
            child: Text('加载中......'),
          ));
    }
  }

  @override
  Widget build(BuildContext context) {
//注意用ScreenAdaper必须得在build方法里面初始化
// 已经在根路径初始化过了，这里就不需要了
// ScreenAdaper.init(context);
//计算右侧GridView宽高比
//左侧宽度
    var leftWidth = ScreenAdaper.getScreenWidth() / 4;
//右侧每一项宽度=（总宽度-左侧宽度-GridView外侧元素左右的Padding值-GridView中间的间距）/3

    var rightItemWidth =
        (ScreenAdaper.getScreenWidth() - leftWidth - 20 - 20) / 3;

//获取计算后的宽度
    rightItemWidth = ScreenUtil().setWidth(rightItemWidth);
//获取计算后的高度
    var rightItemHeight = rightItemWidth + ScreenUtil().setHeight(50);

    return Row(
      children: <Widget>[
        _leftCateWidget(leftWidth),
        _rightCateWidget(rightItemWidth, rightItemHeight)
      ],
    );
  }
}
